/**
 *  Resource：https://leetcode-cn.com/problems/reverse-linked-list/
 *  解题思路：遍历法，核心思想是：将当前节点的next指向它的上一个节点
 * @author junzhongliu
 * @date 2018/12/21 13:53
 */
public class ReverseList {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode1.setNext(listNode2);
        listNode2.setNext(listNode3);
        listNode3.setNext(listNode4);
        listNode4.setNext(listNode5);
        listNode5.setNext(null);
        System.out.println("原链表===="+ listNode1.toString());

        ListNode listNode = reverseList(listNode1);
        System.out.println("反转之后的链表===="+ listNode.toString());
    }

    /**
     * 反转链表
     * @param head
     * @return
     */
    public static ListNode reverseList(ListNode head){
        //定义当前节点为头节点
        ListNode current = head;
        //定义上一个节点为null
        ListNode previous = null;
        if(head==null){
            return null;
        }
        while (current!=null){
            //先获取next节点
            ListNode nextListNode = current.next;
            current.next = previous;
            previous = current;
            current = nextListNode;
        }
        return previous;
    }
}
